package com.wwwc.index.web.servlet;

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import com.wwwc.util.web.*;
import com.wwwc.index.web.ejb.database.*;
import java.rmi.RemoteException;

public class TopBarBean {
    private StringBuffer user_message;
    private StringBuffer error_message;
    private EJBDatabaseQuery ejbdb;

    public StringBuffer getUserMessage() {
	return user_message;
    }
    public StringBuffer getError() {
	return error_message;
    }

    public StringBuffer formatTopBarMessage(String text, String bname) 
    {
	return (formatTopBarMessage(new StringBuffer(text), bname));
    }
    public StringBuffer formatTopBarMessage(StringBuffer text_bf, String bname) 
    {
	StringBuffer sbf = new StringBuffer ();
	sbf.append("\n<CENTER>");
	sbf.append("\n<TABLE cellSpacing='0' cellPadding='3' border='0' style='font-size: 8pt' height='70'>");
	sbf.append("\n<TR><TD align='center' style='font-size: 14pt'>");
	sbf.append(text_bf);
	sbf.append("\n</TD>");
	if(bname != null && bname.length()>1) {
	    sbf.append("\n<TD align=left>");
	    sbf.append("\n<input type=button name=B value="+bname+" style='font-size: 8pt' onClick=history.go(-1);>");
	    sbf.append("\n</TD>");
	}
	sbf.append("\n</TR></TABLE>");
	sbf.append("\n</CENTER>");
	return sbf;
    }

    public StringBuffer activationRequired() 
    {
	StringBuffer sb = new StringBuffer ();
	sb.append("\n<TABLE cellSpacing=0 cellPadding=0 border=0 width=100% style='font-size: 8pt' height=70>");
	sb.append("\n<TR><TD align=center style='font-size: 14pt'>");
	sb.append("\n<img src=/images/star.gif>Activation is required! ");
	sb.append("\n<BR>A verification link and code has been sent to your e-mail.");
	sb.append("\n</TD></TR></TABLE>");
	return sb;
    }

    public StringBuffer getLoginForm(boolean show_forgot, String submit_id, String call_path, String user_ip) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("\n<CENTER>");
	if(user_ip.equals("192.168.1.103")) {
	    sbf.append("\n<TABLE border='0' height='40'  cellSpacing='2' cellPadding='3'>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<FORM method='post' name='signInForm' action='"+call_path+"'>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Username</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("<input type='text' name='username' value='William' size='21' maxlength='20'></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Password</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("\n<input type='password' name='password' value='li0577' size='21' maxlength='20')></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color:#FFFFFF'>");
	    sbf.append("\n<A href=javascript:document.signInForm.submit(); ");
	    sbf.append(" style='color: #FFFFFF; font-size: 12pt'><B>Sign In</B></A></TD>");
	    sbf.append("\n<input type='hidden' name='tid' value='sign_in_check'>");
	    sbf.append("\n<input type='hidden' name='submit_id' value='"+submit_id+"'>");
	    sbf.append("\n</FORM>");
	    sbf.append("\n</TD></TR></TABLE>");

	    sbf.append("\n<TABLE border='0' height='40'  cellSpacing='2' cellPadding='3'>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<FORM method='post' name='signInForm2' action='"+call_path+"'>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Username</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("<input type='text' name='username' value='James-Lee' size='21' maxlength='20'></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Password</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("\n<input type='password' name='password' value='li0578' size='21' maxlength='20')></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color:#FFFFFF'>");
	    sbf.append("\n<A href=javascript:document.signInForm2.submit(); ");
	    sbf.append(" style='color: #FFFFFF; font-size: 12pt'><B>Sign In</B></A></TD>");
	    sbf.append("\n<input type='hidden' name='tid' value='sign_in_check'>");
	    sbf.append("\n<input type='hidden' name='submit_id' value='"+submit_id+"'>");
	    sbf.append("\n</FORM>");
	    sbf.append("\n</TD></TR></TABLE>");

	    sbf.append("\n<TABLE border='0' height='40'  cellSpacing='2' cellPadding='3'>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<FORM method='post' name='signInForm3' action='"+call_path+"'>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Username</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("<input type='text' name='username' value='username' size='21' maxlength='20'></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Password</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("\n<input type='password' name='password' value='li0578' size='21' maxlength='20')></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color:#FFFFFF'>");
	    sbf.append("\n<A href=javascript:document.signInForm3.submit(); ");
	    sbf.append(" style='color: #FFFFFF; font-size: 12pt'><B>Sign In</B></A></TD>");
	    sbf.append("\n<input type='hidden' name='tid' value='sign_in_check'>");
	    sbf.append("\n<input type='hidden' name='submit_id' value='"+submit_id+"'>");
	    sbf.append("\n</FORM>");
	    sbf.append("\n</TD></TR></TABLE>");
	}
	else {
	    sbf.append("\n<TABLE border='0' height='40'  cellSpacing='2' cellPadding='3'>");
	    sbf.append("\n<TR>");
	    sbf.append("\n<FORM method='post' name='signInForm' action='"+call_path+"'>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Username</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("<input type='text' name='username' value='' size='21' maxlength='20'></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'><B>Password</B></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color: #FFFFFF'>");
	    sbf.append("\n<input type='password' name='password' value='' size='21' maxlength='20')></TD>");
	    sbf.append("\n<TD align='center' bgcolor='#6600FF' style='color:#FFFFFF'>");
	    sbf.append("\n<A href=javascript:document.signInForm.submit(); ");
	    sbf.append(" style='color: #FFFFFF; font-size: 12pt'><B>Sign In</B></A></TD>");
	    sbf.append("\n<input type='hidden' name='tid' value='sign_in_check'>");
	    sbf.append("\n<input type='hidden' name='submit_id' value='"+submit_id+"'>");
	    sbf.append("\n</FORM>");
	    sbf.append("\n</TD></TR></TABLE>");
	}
	if(show_forgot) {
	    sbf.append("\n<TABLE>");
	    sbf.append("\n<TR><TD align='center'>");
	    sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	    sbf.append("\n<TD align='left'>");
	    sbf.append("\n<input type='image' src='/images/forgot_passwd.gif' border='0'></TD>");
	    sbf.append("\n<input type='hidden' name='tid' value='forgot_pass'>");
	    sbf.append("\n</FORM>");
	    sbf.append("\n</TD></TR></TABLE>");
	}
	sbf.append("\n</CENTER>");
	return sbf;
    }

    public boolean checkUsernamePassword(String username, String password) {
	if(username == null || username.length()<1 || password == null || password.length()<1) {
	    return false;
	}

	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}

	try {
	    String temp = ejbdb.selectSingleFieldValue("SELECT PASSWD FROM USERS WHERE USERNAME='"+username+"';","PASSWD");
	    System.out.println("user_input="+password);
	    System.out.println("database="+temp);

	    if(temp != null && temp.length()>1 && temp.equals(password)) {
		return true;
	    }
	}
	catch(RemoteException se) {
	    return false;
	}
	return false;
    }

    public boolean setUserProfile (HttpServletRequest request, String username, String user_ip) {
	HttpSession session = request.getSession(true);
	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}

	try {
	    String query = "SELECT * FROM USER_INFO WHERE USERNAME='"+username+"' ORDER BY JOINDAY;";
	    Hashtable temphash = ejbdb.selectSingleRecordHashtable(query);

	    if(temphash != null) {
		if(temphash.get("STATUS").equals("N")) {
		    user_message = activationRequired();
		    return false;
		}

		Hashtable user_info = new Hashtable();
		user_info.put("user_name", temphash.get("USERNAME"));
		user_info.put("user_age", MyDateAndTime.getUserAge((String)temphash.get("BIRTHDAY")));
		user_info.put("user_email", temphash.get("EMAIL"));
		user_info.put("user_fname", temphash.get("FIRSTNAME"));
		user_info.put("user_lname", temphash.get("LASTNAME"));
		user_info.put("user_since", temphash.get("JOINDAY"));
		user_info.put("user_sex", temphash.get("GENDER"));
		user_info.put("user_edu", temphash.get("EDUCATION"));
		user_info.put("user_zip", temphash.get("ZIPCODE"));
		user_info.put("user_level", temphash.get("FIELD11"));
		user_info.put("last_login", temphash.get("FIELD13"));
		user_info.put("last_ip", temphash.get("FIELD14"));

		user_message = new StringBuffer("Last login:"+temphash.get("FIELD13")+" From:"+temphash.get("FIELD14"));
		//clean sidebar object in session allow sidebar refresh
		//session.setAttribute("ContralOpenClose", null);
		//session.setAttribute("SideBarKeys", null);

		session.setAttribute("user_info",user_info);
		session.getAttribute("user_info");

		query = "UPDATE USER_INFO SET "+
		    "FIELD12='"+session.getId()+"',"+
		    "FIELD13='"+System.currentTimeMillis()+"',"+
		    "FIELD14='"+user_ip+"' "+
		    " WHERE USERNAME='"+username+"' AND STATUS='Y';";
		ejbdb.update(query);
		//System.out.println("user_info="+session.getAttribute("user_info"));
	    }
	    else {
		user_message = new StringBuffer("Please try again! Error[201].");
		return false;
	    }
	}
	catch(RemoteException se) {
	    user_message = new StringBuffer("Please try again! Error[202]");
	    return false;
	}

	return true;
    }

    public StringBuffer emailUserInfo(HttpServletRequest request) {
	HttpSession session = request.getSession(true);

	String email   = request.getParameter("email");
	String form_id = request.getParameter("form_id");

	StringBuffer error = null;
	StringBuffer sbf   = new StringBuffer();
	//String call_path   = request.getServletPath();
	String call_path = request.getContextPath()+request.getServletPath();
	if(email != null && form_id != null) {
	  
	    MyUserInputCheck ck = new MyUserInputCheck();
	    if(!ck.checkEmail(email)) {
		error = new StringBuffer("E-mail format error!");
	    }

	    if(error == null) {
		if(!form_id.equals(session.getId())) {
		    System.out.println("TopBarBean:Error:form_id <> session id");
		    return null;
		}
	    }

	    if(error == null) {
		try {
		    if (ejbdb == null) {
			ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
		    }

		    String query = "SELECT USERNAME, FIELD11 FROM USER_INFO WHERE EMAIL='"+
			email+"' AND STATUS='Y' ORDER BY JOINDAY DESC;";
		    ArrayList alist = ejbdb.select(query);

		    if(alist== null || alist.isEmpty()) {
			error = new StringBuffer("System can not find your record.");
		    }

		    if(error == null) {
			StringBuffer email_sbf = new StringBuffer();
			String username  = null;
			String password  = null;
			String userlevel = null;

			Iterator it = alist.iterator();
			ArrayList a = null;
			while (it.hasNext()) {
			    a = (ArrayList)it.next();
			    username  = ""+a.get(0);
			    userlevel = ""+a.get(1);

			    query = "SELECT PASSWD FROM USERS WHERE USERNAME='"+username+"';";
			    password = ejbdb.selectSingleFieldValue(query, "PASSWD");

			    if(password != null && password.length()>1) {
				email_sbf.append("   Account Information\n");
				email_sbf.append("=============================\n");
				email_sbf.append("Username :\t"+username+"\n");
				email_sbf.append("Password :\t"+password+"\n");
				email_sbf.append("Ac.Level :\t"+userlevel+"\n");
				email_sbf.append("=============================\n");
			    }
			}
			if(email_sbf.length()==0) {
			    error = new StringBuffer("System can not find your record.");
			}
			else {
			    email_sbf.append("\n\n-- 3WCenter.com\n"+(new Date()));

			    String from     = "Services@3WCenter.com";
			    String euser    = "Verification";
			    String epass    = "LiNguyen5788";
			    String subject  = "3WCenter.com Account Information";        

			    try {
				SendMail smail = new SendMail();
				if(!smail.send(from, euser, epass, email, subject, email_sbf.toString())) {
				    error = new StringBuffer("Sendding E-mail Error. Please try again later.");
				}
				else {
				    sbf.append("<CENTER><BR/><H3>Your account information has been sent to: ["+email+"].</H3></CENTER>");
				    return sbf;
				}
			    }
			    catch (Exception e) {
				error = new StringBuffer("Sendding E-mail Error. Please try again later.");
			    }  
			}
		    }
		}
		catch (Exception e) {
		    error = new StringBuffer("Error. Please try again later.");
		    System.out.println("TopBarBean:emailUserInfo:Error:"+e);
		}     
	    }
	}

	form_id = session.getId();
	if(error != null) {
	    sbf.append("<CENTER><BR><H3><img src='/images/star.gif' border='0'>"+error+"</H3></CENTER>");
	}

	sbf.append("\n<FORM name='getUserInfoForm' method='post' action='"+call_path+"'>");
	sbf.append("\n<TABLE align='center' cellSpacing='0' cellPadding='5' border='10'>");
	sbf.append("\n<TR>");
	sbf.append("\n<TD align='right'><B>Email:</B></TD>");
	sbf.append("\n<TD align='center'><input type='text' name='email' value='' size='30' maxlength='50'></TD>");
	sbf.append("<TD><A href='javaScript:document.getUserInfoForm.submit();'><B>Submit</B></A></TD>");
	sbf.append("\n</TR>");
	sbf.append("\n</TABLE><BR><BR><BR>");
	sbf.append("\n<input type='hidden' name='tid' value='forgot_pass'>");
	sbf.append("\n<input type='hidden' name='form_id' value='"+form_id+"'>");
	sbf.append("\n</FORM>");
	return sbf;
    }

    public StringBuffer resetUrl (String url) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("\n<SCRIPT>");
	sbf.append("\n\t top.location.replace(\""+url+"\");");
	sbf.append("\n</SCRIPT>");
	return sbf;
    }

    public StringBuffer resetUrl (String form_action, StringBuffer hiddens) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("<FORM name='resetUrl' method='post' action='"+form_action+"'>");
	sbf.append(hiddens);
	sbf.append("</FORM>");
	sbf.append("\n<SCRIPT>");
	sbf.append("\n\t document.resetUrl.submit();");
	sbf.append("\n</SCRIPT>");
	
	return sbf;
    }

    public StringBuffer resetUrl (String url, String set_history) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("\n<SCRIPT>");
	sbf.append("\n\t widnow.history.forward(1);");
	sbf.append("\n\t top.location.replace(\""+url+"\");");
	sbf.append("\n</SCRIPT>");
	return sbf;
    }

    public StringBuffer getTopAd (String call_path, String id, String sid, int adv_position, String user_name) {
	StringBuffer sbf = null;
	
	if(id != null) {
	    sid=id;
	}

	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}

	try {
	    long ct = System.currentTimeMillis();
	    String query = "SELECT * FROM ADS WHERE START_TIME <"+ ct +" AND END_TIME>"+ct+" AND SID='"+sid+"' AND POSITION=1;";
	    ArrayList a = ejbdb.selectSingleRecord(query);
	    sbf = new StringBuffer();
	   
	    if(a != null && a.size()>3) {
		sbf.append("<A href=t?tid=adv&adv_sid="+sid+"&adv_position="+a.get(6)+"&adv_id="+a.get(0)+" target=_blank>");
		sbf.append("<img src="+a.get(2)+" width=760 height=90 border=0></A>");
	    }
	    else {
		sbf.append("<A href="+call_path+"?mid=adv&adv_sid="+sid+"&adv_position="+adv_position+">");
		//sbf.append("<img src=/images/adv/default"+adv_position+".gif border=0></A>");
		sbf.append("<img src=/images/adv/3wcenter.gif border=0></A>");
	    }
	}
	catch(IOException e) {
	}
	
	return sbf;
    }

    public boolean updateAdPageCounter (String adv_id) {
	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}

	try {
	    String query = "SELECT PAGE_COUNTER FROM ADS WHERE ID="+adv_id+";";
	    String temp = ejbdb.selectSingleFieldValue(query, "PAGE_COUNTER");
	    int count = 1;
	    if(temp != null && temp.length()>0) {
		count = Integer.parseInt(temp);
	    }
	    
	    query = "UPDATE ADS SET PAGE_COUNTER="+(count+1)+" WHERE ID="+adv_id+";";
	    ejbdb.update(query);
	}
	catch(IOException e) {
	    System.out.println("TopBerBean:updateAdPageCounter:Error:"+e);
	}
	return true;
    }

    public boolean updateAdCounter (String adv_id) {	
	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}
	
	try {
	    String query = "SELECT COUNTER FROM ADS WHERE ID="+adv_id+";";
	    String temp = ejbdb.selectSingleFieldValue(query, "COUNTER");
	    int count = 1;
	    if(temp != null && temp.length()>0) {
		count = Integer.parseInt(temp);
	    }
	    query = "UPDATE ADS SET COUNTER="+(count+1)+" WHERE ID="+adv_id+";";
	    ejbdb.update(query);
	}
	catch(IOException e) {
	    System.out.println("TopBarBean:updateAdCounter:Error:"+e);
	}
	return true;
    }

    public StringBuffer replaceTopUrl(String adv_id) {
	StringBuffer sbf = new StringBuffer();
	String url = null;

	if(ejbdb == null) {
	    ejbdb = (new DatabaseEJBQuery()).getEJBDatabaseQuery();
	}
	
	try {
	    String query = "SELECT LINK FROM ADS WHERE ID="+adv_id+";";
	    url = ejbdb.selectSingleFieldValue(query, "LINK");
	}
	catch(IOException e) {
	    System.out.println("TopBarBean:updateAdCounter:Error:"+e);
	}
	sbf.append("\n<SCRIPT>");
	sbf.append("\n\t top.location.replace(\""+url+"\");");
	sbf.append("\n</SCRIPT>");
	return sbf;
    }
}






